<script setup>
import IndexDetail from '@v/data-converge/indicator-manage/add/IndexDetail.vue'
import AddDimension from '@v/data-converge/indicator-manage/add/AddDimension.vue'
import { nextTick, provide, ref, getCurrentInstance } from 'vue'
import AddView from '@v/data-converge/indicator-manage/add/AddView.vue'
import AddIndex from '@v/data-converge/indicator-manage/add/AddIndex.vue'
import { v4 } from 'uuid'
import { deleteIndexCatalog } from '@api/city-index'
import { Message } from 'element-ui'

const props = defineProps({
  disabled: Boolean,
})

const rightShow = ref(false)

const addDimensionDialogVisible = ref(false)
const addViewDialogVisible = ref(false)
const addIndexDialogVisible = ref(false)

const addDimensionRef = ref()
const addViewRef = ref()
const addIndexRef = ref()

const isEdit = ref(false)

const indexTree = ref([])
const treeRef = ref()

const currentDimension = ref({})
const currentView = ref({})
const currentIndex = ref({})

const handleAddDimension = () => {
  addDimensionDialogVisible.value = true
}

const handleAddView = () => {
  addViewDialogVisible.value = true
}

const handleAddIndex = () => {
  addIndexDialogVisible.value = true
}

const handleClosed = () => {
  addDimensionDialogVisible.value = false
  addDimensionRef.value.inputData({
    name: '',
    icon: '',
  })
}

const handleViewClosed = () => {
  addViewDialogVisible.value = false
  currentDimension.value = {}
  addViewRef.value.inputData({
    name: '',
    remark: '',
  })
}

const handleIndexClosed = () => {
  addIndexDialogVisible.value = false
  currentView.value = {}
  addIndexRef.value.inputData({
    name: '',
  })
}

const handleAddDimensionConfirm = (data) => {
  if (isEdit.value) {
    Object.assign(currentDimension.value, data)
    addDimensionDialogVisible.value = false
    isEdit.value = false
    return
  }
  // console.log(data)
  indexTree.value.push({
    ...data,
    level: 1,
    children: [],
  })
  addDimensionDialogVisible.value = false
  addDimensionRef.value.inputData({
    name: '',
    icon: '',
  })
}

const handleAddViewConfirm = (data) => {
  if (isEdit.value) {
    Object.assign(currentView.value, data)
    addViewDialogVisible.value = false
    isEdit.value = false
    return
  }
  currentDimension.value.children.push({
    ...data,
    level: 2,
    children: [],
  })
  addViewDialogVisible.value = false
  currentDimension.value = {}
  addViewRef.value.inputData({
    name: '',
    remark: '',
  })
}

const handleAddIndexConfirm = (data) => {
  if (isEdit.value) {
    Object.assign(currentIndex.value, data)
    addIndexDialogVisible.value = false
    isEdit.value = false
    return
  }
  const tempId = v4().replaceAll('-', '')
  currentView.value.children.push({
    ...data,
    level: 3,
    tempId: tempId,
    indexEvaluateRels: [], // 评价标准
    indexDataRels: [], // 数据项
    indexInformationRel: {
      indexParaphrase: '',
      indexUnit: '',
      indexType: '',
    }, // 指标信息
    indexFormulaRelList: [], // 公式信息
  })
  addIndexDialogVisible.value = false
  currentView.value = {}
  addIndexRef.value.inputData({
    name: '',
  })
}

const treeProps = {
  label: 'name',
}

const handleNodeClick = (data) => {
  // if (currentTreeKey.value) {
  //   treeRef.value.setCurrentKey(currentTreeKey.value)
  // } else {
  //   currentTreeKey.value = data.pkid
  // }
  // console.log(data)
  rightShow.value = data.level === 3
  if (data.level === 3) {
    currentIndex.value = data
  } else {
    currentIndex.value = {}
  }
}

const addViewData = (data) => {
  currentDimension.value = data
  handleAddView()
}

const editDimension = (data) => {
  isEdit.value = true
  addDimensionDialogVisible.value = true
  addDimensionRef.value.inputData({
    name: data.name,
    icon: data.icon,
  })
  currentDimension.value = data
}

const handleEditView = (data) => {
  isEdit.value = true
  addViewDialogVisible.value = true
  addViewRef.value.inputData({
    name: data.name,
    remark: data.remark,
  })
  currentView.value = data
}

const handleEditIndex = (data) => {
  isEdit.value = true
  addIndexDialogVisible.value = true
  addIndexRef.value.inputData({
    name: data.name,
  })
  currentIndex.value = data
}

const templateRef = getCurrentInstance()

const removeTreeChildren = (level, node, data) => {
  if (level === 1) {
    const index = indexTree.value.findIndex((item) => item === data)
    indexTree.value.splice(index, 1)
  } else {
    const parentRef = node.parent.data.children
    const index = parentRef.findIndex((item) => item === data)
    parentRef.splice(index, 1)
  }
}

const delNode = (node, data) => {
  templateRef.proxy
    .$confirm('此操作将永久删除该目录, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      if (data.pkid) {
        //
        deleteIndexCatalog(data.pkid).then((res) => {
          if (res.success) {
            Message.success('删除目录成功！')
            removeTreeChildren(data.level, node, data)
            rightShow.value = false
          } else {
            Message.error(res.message)
          }
        })
      } else {
        Message.success('删除目录成功！')
        removeTreeChildren(data.level, node, data)
        rightShow.value = false
      }
    })
}

const addIndicator = (data) => {
  currentView.value = data
  handleAddIndex()
}

// 添加评价标准
const addIndexEvaluate = (data) => {
  currentIndex.value.indexEvaluateRels.push(data)
}

// 添加数据项
const addIndexData = (data) => {
  currentIndex.value.indexDataRels.push(data)
}

// 获取公式信息
const getIndexFormula = (data) => {
  return currentIndex.value.indexFormulaRelList
}

// 改变评价标准
const changeIndexEvaluate = (index, key, value) => {
  currentIndex.value.indexEvaluateRels[index][key] = value
}

// 改变数据项
const changeIndexData = (index, key, value) => {
  currentIndex.value.indexDataRels[index][key] = value
}

const deleteDataItem = (pkid) => {
  currentIndex.value.indexDataRels = currentIndex.value.indexDataRels.filter(
    (item) => item.pkid !== pkid
  )
}

const deleteEvaluateIndex = (index) => {
  currentIndex.value.indexEvaluateRels.splice(index, 1)
}

// 改变指标信息
const changeIndexInfo = (key, value) => {
  currentIndex.value.indexInformationRel[key] = value
  // console.log(currentIndex.value)
}

provide('link', {
  addIndexEvaluate,
  addIndexData,
  changeIndexEvaluate,
  changeIndexInfo,
  changeIndexData,
  deleteDataItem,
  deleteEvaluateIndex,
  getIndexFormula,
})

const getValues = () => {
  return indexTree.value
}

const setChoose = (bool) => {
  if (bool) {
    if (currentIndex.value) {
      currentIndex.value.choose = true
    }
  } else {
    if (currentIndex.value) {
      delete currentIndex.value.choose
    }
  }
}

const inputData = (arr, refId) => {
  indexTree.value = arr.sort((a, b) => {
    return a.orderIndex - b.orderIndex
  })
  rightShow.value = false
  if (refId) {
    indexTree.value.forEach((item) => {
      if (item.children.length) {
        item.children.forEach((child) => {
          if (child.children.length) {
            child.children.forEach((index) => {
              if (index.level === 3 && index.pkid === refId) {
                rightShow.value = true
                currentIndex.value = index
                nextTick(() => {
                  treeRef.value.setCurrentKey(index.pkid)
                })
              }
            })
          }
        })
      }
    })
  }
  // rightShow.value = false
  if (props.disabled) {
    let isFirst = true
    indexTree.value.forEach((item) => {
      if (item.children.length) {
        item.children.forEach((child) => {
          if (child.children.length) {
            child.children.forEach((index) => {
              if (index.level === 3 && isFirst) {
                // console.log(index)
                rightShow.value = true
                currentIndex.value = index
                isFirst = false
                nextTick(() => {
                  treeRef.value.setCurrentKey(index.pkid)
                })
              }
            })
          }
        })
      }
    })
  }
}

defineExpose({
  getValues,
  inputData,
  setChoose,
})
</script>

<template>
  <div class="index">
    <div class="content-title">
      <svg-icon icon-class="标题图标" />
      <span>指标体系</span>
    </div>
    <div class="wrap">
      <div class="left">
        <div class="title-content">
          <div class="title">指标维度</div>
          <div class="add-index" @click="handleAddDimension" v-show="!disabled">
            <svg-icon icon-class="addIndex" />
            <p>新增维度</p>
          </div>
        </div>
        <el-tree
          :data="indexTree"
          node-key="pkid"
          ref="treeRef"
          :props="treeProps"
          class="dimension-tree"
          :highlight-current="true"
          :default-expand-all="true"
          :expand-on-click-node="false"
          empty-text="请先添加维度"
          @node-click="handleNodeClick"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <div class="custom-tree-node-title">
              <img v-if="data.level === 1" :src="data.icon" />
              <span v-else style="width: 7px"></span>
              <span style="width: 180px" class="overflow-point">{{
                node.label
              }}</span>
            </div>
            <span v-show="!disabled">
              <template v-if="data.level === 1">
                <el-tooltip effect="dark" content="添加视角" placement="top">
                  <svg-icon
                    icon-class="添加子目录"
                    @click.stop="addViewData(data)"
                  ></svg-icon>
                </el-tooltip>
                <el-tooltip effect="dark" content="编辑维度" placement="top">
                  <svg-icon
                    icon-class="编辑"
                    @click.stop="editDimension(data)"
                  ></svg-icon>
                </el-tooltip>
              </template>
              <template v-if="data.level === 2">
                <el-tooltip effect="dark" content="添加指标" placement="top">
                  <svg-icon
                    icon-class="添加子目录"
                    @click.stop="addIndicator(data)"
                  ></svg-icon>
                </el-tooltip>

                <el-tooltip effect="dark" content="编辑视角" placement="top">
                  <svg-icon
                    icon-class="编辑"
                    @click.stop="handleEditView(data)"
                  ></svg-icon>
                </el-tooltip>
              </template>
              <template v-if="data.level === 3">
                <el-tooltip effect="dark" content="编辑指标" placement="top">
                  <svg-icon
                    icon-class="编辑"
                    @click.stop="handleEditIndex(data)"
                  ></svg-icon>
                </el-tooltip>
              </template>

              <el-tooltip effect="dark" content="删除" placement="top">
                <!--                `确定删除该${-->
                <!--                  scope.row.level === 1-->
                <!--                    ? '维度'-->
                <!--                    : scope.row.level === 2-->
                <!--                    ? '视角'-->
                <!--                    : '指标'-->
                <!--                }吗？`-->
                <svg-icon
                  icon-class="删除"
                  @click.stop="delNode(node, data)"
                ></svg-icon>
              </el-tooltip>
            </span>
          </span>
        </el-tree>
      </div>
      <div class="right">
        <index-detail
          v-show="rightShow"
          :indexInfo="currentIndex"
          :show="rightShow"
          :disabled="disabled"
        />
        <el-empty v-show="!rightShow" description="请先选择指标" />
      </div>
    </div>

    <add-dimension
      :visible="addDimensionDialogVisible"
      @closed="handleClosed"
      @confirm="handleAddDimensionConfirm"
      ref="addDimensionRef"
    />
    <add-view
      :visible="addViewDialogVisible"
      @closed="handleViewClosed"
      @confirm="handleAddViewConfirm"
      ref="addViewRef"
    />
    <add-index
      ref="addIndexRef"
      :visible="addIndexDialogVisible"
      @closed="handleIndexClosed"
      @confirm="handleAddIndexConfirm"
    />
  </div>
</template>

<style scoped lang="scss">
.index {
  //height: calc(100% - 360px);
  .wrap {
    height: 100%;
    padding: 20px 16px 0 16px;
    display: flex;

    .left {
      width: 302px;
      overflow-y: auto;
      background: #f5f8fe;
      border-radius: 1px;
      border: 1px solid #f3f3f9;
      padding: 14px 18px;
      max-height: 600px;

      .title-content {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .title {
          font-weight: bold;
          font-size: 14px;
          color: #4e525f;
          display: flex;
          align-items: center;

          &::before {
            content: '';
            width: 4px;
            height: 12px;
            background: #10a6dd;
            margin-right: 4px;
          }
        }

        .add-index {
          cursor: pointer;
          height: 12px;
          font-weight: 400;
          font-size: 14px;
          color: #10a6dd;
          display: flex;
          align-items: center;
          p {
            margin-left: 2px;
          }
        }
      }

      :deep(.el-tree) {
        background-color: transparent;
      }

      :deep(.dimension-tree) {
        margin-top: 17px;
        .custom-tree-node {
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: space-between;
          font-size: 15px;
          padding-right: 8px;

          .custom-tree-node-title {
            display: flex;
            align-items: center;

            img {
              width: 20px;
              fill: #c0c4cc;
              display: inline-block;
              margin-right: 5px;
            }
          }
        }

        .el-tree-node.is-current > .el-tree-node__content {
          color: #10a6dd;
          background: rgba(255, 255, 255, 0.6) !important;
          box-shadow: 0px 0px 4px 0px rgba(225, 225, 225, 0.74) !important;
        }
      }
    }

    .right {
      border: 1px solid #f3f3f9;
      flex: 1;
    }
  }

  .overflow-point {
    // 溢出打点显示
    white-space: nowrap; /* 确保文本在一行内显示 */
    overflow: hidden; /* 隐藏溢出的内容 */
    text-overflow: ellipsis; /* 使用省略号显示文本溢出的部分 */
  }
}
</style>
